import { defineStore } from 'pinia'
import { ref } from 'vue'

// 定义用户信息接口
interface UserInfo {
  id: number
  username: string
  avatar: string
  super: number
  role: Role
  menus: Menu[]
  ruleNames: string[]
}

interface Menu {
  id: number
  rule_id: number
  status: number
  create_time: string
  update_time: string
  name: string
  desc: null | string
  frontpath: null | string
  condition: null | string
  menu: number
  order: number
  icon: string
  method: string
  child: Child[]
}

interface Child {
  id: number
  rule_id: number
  status: number
  create_time: string
  update_time: string
  name: string
  desc: null | string
  frontpath: string
  condition: null | null | string | string
  menu: number
  order: number
  icon: string
  method: string
  child: any[]
}

interface Role {
  id: number
  name: string
}

export const useUserStore = defineStore(
  'user',
  () => {
    // 用户信息
    const userInfo = ref<UserInfo>()
    // 登录状态
    const isLogin = ref<boolean>(false)
    const token = ref<string>('')

    const setToken = (t: string) => {
      token.value = t
    }

    // 设置用户信息
    function setUserInfo(info: UserInfo): void {
      userInfo.value = info
    }

    // 设置登录状态
    function setUserLoginState(state: boolean): void {
      isLogin.value = state
    }

    // 清除用户信息（用于登出）
    function clearUserInfo(): void {
      token.value = ''
      userInfo.value = undefined
      isLogin.value = false
    }

    return {
      userInfo,
      isLogin,
      token,
      setToken,
      setUserInfo,
      setUserLoginState,
      clearUserInfo
    }
  },
  {
    persist: true // 启用持久化存储，这样刷新页面后用户信息不会丢失
  }
)
